package com.ibm.sova.abcd.cma;

import org.apache.log4j.Logger;

/**
 * This is a command line utility that can be used to run this application.
 * 
 * Thread Safety: it is immutable and thread safe
 */
public class ABCDWebToolCMAUtility {
    /**
     * Represents the logger to perform logging.
     */
    private static Logger LOGGER = Logger.getLogger(ABCDWebToolCMAUtility.class);

    /**
     * Private constructor preventing construction of this class.
     */
    private ABCDWebToolCMAUtility() {
    }

    /**
     * Entrance of this utility.
     * 
     * ###Param
     * args - the command line argument list
     * 
     * ###Impl
     * 1. Parse command line argument, find the argument "-f=<config_file>" (note, '<' and '>' are used for clarifty only), get configFile:String. //Note this argument is optional
     * 2. Create an instance of CMAMessageHandler: 
     *     2.1 If configFile is null: handler=new CMAMessageHandler();
     *     2.1 Else: handler=new CMAMessageHandler(configFile);
     * 3. If CMARequestConfigurationException is thrown, log it at ERROR level and return;
     * 4. While TRUE:
     *     4.1 Handle CMA request messages: handler.handleCMAMessage();
     *     4.2 If any exception is thrown, catch it, log it at ERROR level and continue to next loop, DO NOT break the loop.
     * 
     * ###Exceptions
     * None
     * @param args 
     */
    public static void main(String[] args) {
        CMAMessageHandler handler = null;
        String configFile = null;
        for(int index = 0; index < args.length; index++) {
            if(args[index].startsWith("-f=")) {
                configFile = args[index].substring(args[index].indexOf("-f=") + 3);
                break;
            }
        }
        
        try {
            if(configFile == null) {
                handler = new CMAMessageHandler();
            } else {
                handler = new CMAMessageHandler(configFile);
            }
        } catch(CMARequestConfigurationException cmaRequestConfException) {
            LOGGER.error(cmaRequestConfException.getLocalizedMessage());
            return;
        }
        while(true) {
            try {
                handler.handleCMAMessage();
            } catch (CMARequestHandlingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

